package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gocolly/colly"
	"sbd_zgqx/models"
	"sbd_zgqx/service"
	"sbd_zgqx/utils"
)

type WeatherHandler struct {
	WeatherSrv service.WeatherService
}

func (handler WeatherHandler) InsterWeatherHandler() {
	isPro, err := handler.WeatherSrv.ListArea()
	if err != nil {
		fmt.Println("select pro of err")
	}
	node := &utils.SnowFlake{}
	_ = node.Init(1, 5)
	for _, v := range isPro {

		id, _ := node.NextId()
		// fmt.Println(v.ID, v.Serial)
		inert, err := handler.GetWeatherHandler(v.Serial)
		if err != nil {
			fmt.Println("get serial info err:", err)
			return
		}
		inert.ID = id

		is, err := handler.WeatherSrv.InsertWeather(inert)
		if err != nil {
			fmt.Println("insert into weather as ", is, " of err:", err)

		}

	}
	
}

func (handler WeatherHandler) GetWeatherHandler(serial string) (insert models.Weather, err error) {
	var result models.ResultWeather

	urlProvince := fmt.Sprintf("https://weather.cma.cn/api/now/%s", serial)

	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"))

	c.OnRequest(func(r *colly.Request) {
		// r.Headers.Set("Cookie", "JSESSIONID=A87C2BE548AF94B7CC4B9FA8E40178D0; pageSize=20; pageNo=1")
		// r.Headers.Set("Content-Type", " application/x-www-form-urlencoded")

	})
	c.OnResponse(func(r *colly.Response) {
		// fmt.Println(string(r.Body))
		err = json.Unmarshal(r.Body, &result)
		// fmt.Println(string(r.Body))
		if err != nil {
			return
		}
		// fmt.Println(result.Data)

		now, err := json.Marshal(result.Data.Now)
		if err != nil {
			return
		}
		err = json.Unmarshal(now, &insert)
		if err != nil {
			return
		}
		insert.LastUpdate = result.Data.LastUpdate

		insert.Serial = serial

		fmt.Println(insert)
		//
		// as := strings.Split(result.Data, "|")
		// node := &utils.SnowFlake{}
		// _ = node.Init(1, 5)
		// for _, v := range as {
		// 	id, _ := node.NextId()
		// 	area := strings.Split(v, ",")
		// 	isPro.ID = id
		// 	isPro.CID = 000000
		// 	isPro.Serial = utils.ReplaceStr(area[0])
		// 	isPro.Area = utils.ReplaceStr(area[1])
		//
		// 	_, _ = handler.ProvinceSrv.InsterProvinceSrv(isPro)
		//
		// 	handler.ReSerialInfoHandler(isPro.Serial, id)
		// }
		// fmt.Println(as[0])
		// for _, v := range result.Rows {
		// 	v.ID = utils.SnowId()
		// 	v, err = ReListInfoHandler(v)
		// 	if err != nil {
		// 		fmt.Println("bbbb ====>", err)
		// 	}
		// 	isBreeders = append(isBreeders, v)
		// }

	})
	c.Visit(urlProvince)
	return
}
